# coding=utf-8
from flask import Flask,redirect,make_response,send_file
from flask_compress import Compress
import getopt,sys
from module import GlobalData
from module.topic import topic
import logging
from logging.handlers import RotatingFileHandler
import os
logging.basicConfig(level=logging.ERROR)
# 定义一个RotatingFileHandler，最多备份10个日志文件，每个日志文件最大100M
file_log_handler = RotatingFileHandler("logs/error.log", maxBytes=1024 * 1024 * 100, backupCount=10)
file_log_handler.setLevel(logging.ERROR)
formatter = logging.Formatter('[%(asctime)s]-%(threadName)s-%(levelname)s %(pathname)s:%(lineno)d\n%(message)s')
logging.getLogger('').addHandler(file_log_handler)

app_context_path = GlobalData.APP_CONTEXT_PATH
app = Flask(__name__,static_url_path=app_context_path)
Compress(app)

app.secret_key = 'to-be-frank-api'
app.config['SESSION_COOKIE_NAME']='to-be-frank-session-id'
app.register_blueprint(topic,url_prefix='/topic')
@app.route('/')
@app.route('/index')
def index():
    return redirect(app_context_path+'/index.html')
@app.route('/downloadData')
def download_data():
    dbfile = os.getcwd()+'/data/guest.db'
    response = make_response(send_file(dbfile, as_attachment=True, attachment_filename='guest.db'))
    response.headers["Content-Disposition"] = "attachment; filename={}".format(
        'guest.db'.encode().decode('utf8'))
    return response
def get_ip():
    import socket
    return socket.gethostbyname(socket.gethostname())
if __name__ == '__main__':
    opts, args = getopt.getopt(sys.argv[1:], 'h:p:t:d:',
                               ['port=', 'debug=', 'code=','ssl-port=','ssl-host=','use-host-ssl','no-use-ssl=','reloader=','pem-key='])

    pm = {}
    for op, value in opts:
        pm[op[2:]] = value

    debug = True if 'debug' in pm else False
    port = int(pm['port']) if 'port' in pm else 9098
    ssl_port = int(pm['ssl-port']) if 'ssl-port' in pm else 9099
    ssl_host = pm['ssl-host'] if 'ssl-host' in pm else ''
    use_host_ssl = True if 'use-host-ssl' in pm else False
    no_use_ssl = True if 'no-use-ssl' in pm else False
    reloader = True if 'reloader' in pm else False
    pem_key = pm['pem-key'] if 'pem-key' in pm else ''
    host = get_ip()

    if use_host_ssl:
        ssl_context = ("./data/ca/server/" + host + "-server-cert.pem", "./data/ca/server/" + host + "-server-key.pem")
    elif len(ssl_host)>0:
        ssl_context = ("./data/ca/server/" + ssl_host + "-server-cert.pem", "./data/ca/server/" + ssl_host + "-server-key.pem")
    elif len(pem_key)>0:
        ssl_context = (
        "./data/ca/server/" + pem_key + ".cer", "./data/ca/server/" + pem_key + ".key")
    else:
        ssl_context ='adhoc'
    if no_use_ssl:
        ssl_context=None
    else:
        port = ssl_port

    threaded = True  # platform.system()!='Darwin'
    app.run(host='0.0.0.0',
            port=port,
            debug=debug,
            threaded=threaded,
            use_reloader=reloader,
            ssl_context=ssl_context
            )